import { queryPermission } from '@/api/api-login';
import { useLoginStore, useUserInfoStore } from '@/stores/login';
import { storeToRefs } from 'pinia';

const LOGIN_KEYS = {
  USER_TOKEN: '_U_T_',
  USER_INFO: '_U_I_',
};

const LOGIN_URL = import.meta.env.VITE_LOGIN_ORIGIN;

function setCookie(cname: string, cvalue: string, isDelete?: boolean) {
  const deleteFlag = isDelete ? 'max-age=0; ' : '';
  try {
    const domain = import.meta.env.VITE_COOKIE_DOMAIN;
    const expires = `${deleteFlag}path=/; domain=${domain}`;
    document.cookie = `${cname}=${cvalue}; ${expires}`;
  } catch {
    return null;
  }
}

/**
 * 从cookie中获取指定的值
 *
 * @param {string} cname - 目标值字段名
 * @returns {string} 如目标值在cookie中返回值，否则返回null
 */
function getCookie(cname: string) {
  try {
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
      cookie = cookie.trim();
      const [name, value] = cookie.split('=');
      if (name === cname) {
        return decodeURIComponent(value);
      }
    }
    return null;
  } catch {
    return null;
  }
}

/**
 * 删除Cookie中指定字段
 */
function deleteCookie(cname: string) {
  setCookie(cname, 'null', true);
}

/**
 * 存储用户id及token，用于下次登录
 */
export function saveUserAuth(code: string) {
  code ? setCookie(LOGIN_KEYS.USER_TOKEN, code) : deleteCookie(LOGIN_KEYS.USER_TOKEN);
}

/**
 * @returns token 返回用户token
 */
export function getUserAuth() {
  const token = getCookie(LOGIN_KEYS.USER_TOKEN) || '';
  if (!token) saveUserAuth();
  return token;
}

// 退出登录
export function logout() {
  location.href = `${LOGIN_URL}/logout?redirect_uri=${encodeURIComponent(window?.location?.origin)}`;
}

/**
 * 跳转至首页
 */
export function goToHome() {
  window?.location?.reload();
}

/**
 * 跳转至登陆页面进行登录
 */
export function login() {
  location.href = `${LOGIN_URL}/login?redirect_uri=${encodeURIComponent(location.href)}&lang=zh`;
}

/**
 * 跳转至注册页面进行注册
 */
export function register() {
  location.href = `${LOGIN_URL}/register?redirect_uri=${encodeURIComponent(location.href)}&lang=zh`;
}

/**
 * token失效时跳转至首页
 */
export function tokenFailIndicateLogin() {
  saveUserAuth();
  resetLogin();
  goToHome();
}

/**
 * @returns store 将store返回，使用解构赋值接受
 */
export function useStoreData() {
  return storeToRefs(useUserInfoStore());
}

/**
 * 刷新后重新请求登录用户信息
 *
 * @param {string} community - 社区ID
 */
export function refreshInfo(community = 'openubmc') {
  const token = getUserAuth();
  const loginStore = useLoginStore();
  const userStore = useUserInfoStore();
  if (token) {
    loginStore.$patch('LOGINING');
    queryPermission({ community })
      .then((res) => {
        const { data } = res;
        if (Object.prototype.toString.call(data) === '[object Object]') {
          userStore.$patch(data);
          loginStore.$patch('LOGINED');
        }
      })
      .catch(() => {
        resetLogin();
      });
  } else {
    resetLogin();
  }
}

/**
 * 判断是否为有效登录状态
 */
export function isLogined() {
  return new Promise((resolve, reject) => {
    const token = getUserAuth();
    const loginStore = useLoginStore();
    const userStore = useUserInfoStore();
    if (token) {
      queryPermission({ community: 'openubmc' })
        .then((res) => {
          const { data } = res;
          if (data) {
            if (Object.prototype.toString.call(data) === '[object Object]') {
              userStore.$patch(data);
            }
            loginStore.$patch('LOGINED');
            resolve(true);
          } else {
            resetLogin();
            reject(false);
          }
        })
        .catch((err) => {
          resetLogin();
          reject(err);
        });
    } else {
      resetLogin();
      reject(false);
    }
  });
}

/**
 * 根据URL返回当前语言
 */
export function getLanguage() {
  return location.pathname.includes('/zh/') ? { lang: 'zh', language: 'zh-CN' } : { lang: 'en', language: 'en-US' };
}

/**
 * 重置登陆状态及用户信息
 */
export function resetLogin() {
  useLoginStore().$reset();
  useUserInfoStore().$reset();
}
